#!/usr/bin/env python3
"""
修复版游戏颜色触发演示脚本
解决了缓存和检测问题
"""

import time
import pyautogui
from utils.dominant_color_detector import DominantColorDetector

class FixedGameColorTrigger:
    """修复版游戏颜色触发器演示类"""
    
    def __init__(self):
        self.detector = DominantColorDetector(
            region_size=200,      # 检测区域大小
            k_clusters=3,         # K-Means聚类数量
            cache_duration=0.01   # 极短缓存，几乎实时
        )
        self.running = False
        self.trigger_count = 0
        
    def setup_target_color(self):
        """设置目标颜色"""
        print("🎯 设置目标颜色")
        print("请将目标颜色移动到屏幕中心，然后按回车确认...")
        input("按回车继续...")
        
        # 强制清除缓存
        self.detector.clear_cache()
        
        # 获取当前屏幕中心的主要颜色作为目标
        dominant_color, confidence, detection_info = self.detector.get_dominant_color_at_center(use_cache=False)
        
        if dominant_color:
            self.target_color = dominant_color
            print(f"✅ 目标颜色已设置: RGB{self.target_color}")
            print(f"   检测置信度: {confidence:.3f}")
            
            # 显示检测到的所有颜色
            all_colors = detection_info.get('all_colors', [])
            weights = detection_info.get('weights', [])
            
            print(f"   检测区域中的所有颜色:")
            for i, (color, weight) in enumerate(zip(all_colors, weights)):
                marker = "👑" if i == 0 else "  "
                print(f"   {marker} RGB{color} (占比: {weight:.1%})")
            
            return True
        else:
            print("❌ 无法检测到颜色，请重试")
            return False
    
    def start_monitoring(self, tolerance=30, trigger_interval=0.5):
        """开始监控和触发"""
        if not hasattr(self, 'target_color'):
            print("❌ 请先设置目标颜色")
            return
        
        print(f"\n🚀 开始监控颜色触发")
        print(f"   目标颜色: RGB{self.target_color}")
        print(f"   容差: {tolerance}")
        print(f"   触发间隔: {trigger_interval}s")
        print(f"   按 Ctrl+C 停止监控")
        
        self.running = True
        self.trigger_count = 0
        last_trigger_time = 0
        
        try:
            while self.running:
                current_time = time.time()
                
                # 强制清除缓存以确保实时检测
                self.detector.clear_cache()
                
                # 检查颜色匹配 (完全禁用缓存)
                is_match, confidence, detection_info = self.detector.is_color_match_dominant(
                    target_color=self.target_color,
                    tolerance=tolerance
                )
                
                if is_match:
                    # 检查触发间隔
                    if current_time - last_trigger_time >= trigger_interval:
                        self.execute_trigger(detection_info)
                        last_trigger_time = current_time
                        self.trigger_count += 1
                
                # 显示实时状态
                dominant_color = detection_info.get('dominant_color', (0, 0, 0))
                color_distance = detection_info.get('color_distance', 999)
                status = "🎯 匹配" if is_match else "⏳ 监控"
                
                print(f"\r{status} | 目标: RGB{self.target_color} | 当前: RGB{dominant_color} | 距离: {color_distance:.1f} | 触发次数: {self.trigger_count}   ", 
                      end="", flush=True)
                
                time.sleep(0.05)  # 20Hz检测频率，更快响应
                
        except KeyboardInterrupt:
            print(f"\n\n✅ 监控已停止，总触发次数: {self.trigger_count}")
            self.running = False
    
    def execute_trigger(self, detection_info):
        """执行触发动作"""
        try:
            # 执行左键点击
            pyautogui.click()
            
            # 记录触发信息
            dominant_color = detection_info.get('dominant_color', (0, 0, 0))
            confidence = detection_info.get('match_confidence', 0)
            
            print(f"\n🔥 触发! 检测到: RGB{dominant_color}, 置信度: {confidence:.3f}")
            
        except Exception as e:
            print(f"\n❌ 触发执行失败: {e}")

def test_real_time_detection():
    """测试实时检测功能"""
    print("🔍 实时颜色检测测试")
    print("=" * 50)
    print("这个测试将显示屏幕中心的实时颜色变化")
    print("请移动不同颜色的内容到屏幕中心观察")
    print("按 Ctrl+C 停止测试")
    
    detector = DominantColorDetector(region_size=150, k_clusters=3, cache_duration=0.001)
    
    try:
        while True:
            # 强制清除缓存
            detector.clear_cache()
            
            # 获取当前颜色
            dominant_color, confidence, detection_info = detector.get_dominant_color_at_center(use_cache=False)
            
            if dominant_color:
                all_colors = detection_info.get('all_colors', [])
                weights = detection_info.get('weights', [])
                
                # 显示主要颜色
                print(f"\r主要颜色: RGB{dominant_color} (置信度: {confidence:.3f})   ", end="", flush=True)
                
                # 每秒显示一次详细信息
                if int(time.time()) % 2 == 0:
                    print(f"\n详细信息:")
                    for i, (color, weight) in enumerate(zip(all_colors[:3], weights[:3])):
                        marker = "👑" if i == 0 else "  "
                        print(f"   {marker} RGB{color} (权重: {weight:.3f})")
            else:
                print(f"\r检测失败...   ", end="", flush=True)
            
            time.sleep(0.1)  # 10Hz更新
            
    except KeyboardInterrupt:
        print(f"\n\n✅ 实时检测测试结束")

def main():
    """主函数"""
    print("🚀 修复版游戏颜色触发演示程序")
    print("解决了缓存和检测延迟问题")
    print("=" * 50)
    
    # 检查依赖
    try:
        import sklearn
        print(f"✅ 环境检查通过")
    except ImportError:
        print("❌ 缺少依赖: pip install scikit-learn")
        return
    
    print("\n请选择测试模式:")
    print("1. 实时颜色检测测试")
    print("2. 颜色触发演示")
    print("3. 退出")
    
    try:
        choice = input("\n请选择 (1-3): ").strip()
    except:
        choice = "3"
    
    if choice == "1":
        test_real_time_detection()
    elif choice == "2":
        trigger = FixedGameColorTrigger()
        
        if trigger.setup_target_color():
            print(f"\n⚙️ 配置参数:")
            
            try:
                tolerance = int(input("请输入颜色容差 (推荐30-50): ") or "40")
                interval = float(input("请输入触发间隔秒数 (推荐0.3-1.0): ") or "0.5")
            except:
                tolerance = 40
                interval = 0.5
                print(f"使用默认参数: 容差={tolerance}, 间隔={interval}s")
            
            # 开始监控
            trigger.start_monitoring(tolerance=tolerance, trigger_interval=interval)
    else:
        print("👋 再见!")

if __name__ == "__main__":
    main()
